// src/stores/models/ToolKit/toolKitModel.ts
import { types } from "mobx-state-tree";

// 定义表格项模型
const TableItemModel = types.model("TableItem", {
  key: types.string,
  name: types.string,
  description: types.string,
  selected: types.boolean
});

// 定义对比结果模型
const ComparisonResultModel = types.model("ComparisonResult", {
  tableName: types.string,
  status: types.enumeration(["success", "warning", "error"]),
  totalRows: types.number,
  matchedRows: types.number,
  mismatchedRows: types.number,
  missingRows: types.number,
  extraRows: types.number
});

// 定义数据库配置模型
export const DbConfigModel = types.model("DbConfig", {
  host: types.string,
  port: types.string,
  database: types.string,
  username: types.string,
  password: types.string
});

// 定义数据库卡片模型
export const DbCardModel = types.model("DbCard", {
  id: types.number,
  name: types.string,
  config: DbConfigModel,
  isConnected: types.boolean
});

// 定义数据库连接状态模型
export const DbConnectionModel = types.model("DbConnection", {
  isConnected: types.boolean,
  config: DbConfigModel
});

// 定义数据库选择模型
const SelectedDbModel = types.model("SelectedDb", {
  core: types.boolean,
  refactored: types.boolean
});

// 定义标签模型
const TagModel = types.model("Tag", {
  id: types.number,
  name: types.string
});

export const ToolKitModel = types.model("ToolKit", {
  // 添加数据库卡片状态
  dbCards: types.optional(types.array(DbCardModel), [
    {
      id: 1,
      name: '自定义数据库名称',
      config: {
        host: "",
        port: "",
        database: "",
        username: "",
        password: ""
      },
      isConnected: false
    } as any
  ]),
  
  // 添加已连接的数据库卡片状态（用于在已连接区域显示）
  connectedDbCards: types.optional(types.array(DbCardModel), []),
  
  // 添加数据库连接状态
  dbConnections: types.optional(types.model({
    core: DbConnectionModel,
    refactored: DbConnectionModel
  }), {
    core: {
      isConnected: false,
      config: {
        host: "",
        port: "",
        database: "",
        username: "",
        password: ""
      }
    },
    refactored: {
      isConnected: false,
      config: {
        host: "refactored-db.example.com",
        port: "3306",
        database: "production_db",
        username: "admin",
        password: "password"
      }
    }
  }),
  
  // 添加选中的数据库状态
  selectedDbs: types.optional(SelectedDbModel, {
    core: false,
    refactored: false
  }),
  
  // 添加选中的数据库卡片状态（动态数据库选择）
  selectedDbCards: types.optional(types.frozen<Record<string, boolean>>(), {}),
  
  // 添加标签列表
  tags: types.optional(types.array(TagModel), []),
  
  // 添加分享选项
  isShared: types.optional(types.boolean, true),
  
  // 添加DBCompare组件需要的状态
  tables: types.optional(types.array(TableItemModel), [
    { key: "1", name: "users", description: "用户基本信息表", selected: true },
    { key: "2", name: "user_profiles", description: "用户资料表", selected: true },
    { key: "3", name: "user_roles", description: "用户角色关联表", selected: false },
    { key: "4", name: "roles", description: "角色定义表", selected: false },
    { key: "5", name: "permissions", description: "权限定义表", selected: false },
    { key: "6", name: "orders", description: "订单表", selected: false },
    { key: "7", name: "order_items", description: "订单项表", selected: false },
    { key: "8", name: "products", description: "产品表", selected: false },
    { key: "9", name: "categories", description: "产品分类表", selected: true },
    { key: "10", name: "payments", description: "支付记录表", selected: false }
  ]),
  
  results: types.optional(types.array(ComparisonResultModel), [
    { tableName: "users", status: "success", totalRows: 8342, matchedRows: 8342, mismatchedRows: 0, missingRows: 0, extraRows: 0 },
    { tableName: "user_profiles", status: "warning", totalRows: 4521, matchedRows: 4116, mismatchedRows: 405, missingRows: 0, extraRows: 0 },
    { tableName: "categories", status: "error", totalRows: 142, matchedRows: 0, mismatchedRows: 142, missingRows: 83, extraRows: 59 }
  ]),
  
  comparisonScenario: types.optional(types.enumeration(["same-db", "different-db"]), "same-db"),
  
  // 添加SQL格式化开关
  isFormattingEnabled: types.optional(types.boolean, true),
  
  // 表单数据
  sameDbSql: types.optional(types.string, 'select * from user where userid in (11111,22222);\nselect * from order where userid in (11111,22222);'),
  differentDbSql1: types.optional(types.string, 'select * from global.user where userid=11111;'),
  differentDbSql2: types.optional(types.string, 'select * from au.user where userid=222222;'),
  
  // 添加环境配置标签页状态
  activeEnvTab: types.optional(types.enumeration(["db", "var"]), "db"),
  
  // 添加悬停的数据库ID状态
  hoveredDbId: types.maybeNull(types.number)
}).actions(self => ({
  // 添加操作方法
  setTableSelected(key: string, selected: boolean) {
    const table = self.tables.find(t => t.key === key);
    if (table) {
      table.selected = selected;
    }
  },
  
  selectAllTables() {
    self.tables.forEach(table => {
      table.selected = true;
    });
  },
  
  deselectAllTables() {
    self.tables.forEach(table => {
      table.selected = false;
    });
  },
  
  setComparisonScenario(scenario: "same-db" | "different-db") {
    // 检查是否从"不同数据库"场景切换到"同一数据库"场景
    if (scenario === "same-db" && self.comparisonScenario === "different-db") {
      // 检查是否两个数据库都被选中
      if (self.selectedDbs.core && self.selectedDbs.refactored) {
        // 弹出提示并清除所有选中的数据库
        alert("该场景只能选中某个数据库，已自动清除数据库选择。");
        self.selectedDbs.core = false;
        self.selectedDbs.refactored = false;
      }
    }
    
    // 切换场景时清空数据库卡片选择记录
    self.selectedDbCards = {};
    
    self.comparisonScenario = scenario;
  },
  
  setSameDbSql(sql: string) {
    self.sameDbSql = sql;
  },
  
  setDifferentDbSql1(sql: string) {
    self.differentDbSql1 = sql;
  },
  
  setDifferentDbSql2(sql: string) {
    self.differentDbSql2 = sql;
  },
  
  // 标签相关方法
  addTag(name: string) {
    const newId = self.tags.length > 0 ? Math.max(...self.tags.map(t => t.id)) + 1 : 1;
    self.tags.push({ id: newId, name });
  },
  
  removeTag(id: number) {
    const index = self.tags.findIndex(tag => tag.id === id);
    if (index !== -1) {
      self.tags.splice(index, 1);
    }
  },
  
  // 分享选项方法
  setIsShared(isShared: boolean) {
    self.isShared = isShared;
  },
  
  // 数据库选择相关方法
  setDbSelected(db: "core" | "refactored", selected: boolean) {
    self.selectedDbs[db] = selected;
  },
  
  // 动态数据库卡片选择方法
  setDbCardSelected(id: number, selected: boolean) {
    self.selectedDbCards = {
      ...self.selectedDbCards,
      [id]: selected
    };
  },
  
  // 设置整个selectedDbCards对象
  setSelectedDbCards(selectedDbCards: Record<string, boolean>) {
    self.selectedDbCards = selectedDbCards;
  },
  
  selectAllDbs() {
    if (self.dbConnections.core.isConnected) {
      self.selectedDbs.core = true;
    }
    if (self.dbConnections.refactored.isConnected) {
      self.selectedDbs.refactored = true;
    }
    
    // 同时选择所有已连接的数据库卡片
    const newSelectedDbCards: Record<string, boolean> = {};
    self.dbCards
      .filter(card => card.isConnected)
      .forEach(card => {
        newSelectedDbCards[card.id.toString()] = true;
      });
    self.selectedDbCards = newSelectedDbCards;
  },
  
  deselectAllDbs() {
    self.selectedDbs.core = false;
    self.selectedDbs.refactored = false;
    
    // 同时取消选择所有数据库卡片
    self.selectedDbCards = {};
  },
  
  // SQL格式化开关方法
  setFormattingEnabled(enabled: boolean) {
    self.isFormattingEnabled = enabled;
  },
  
  // 更新数据库配置方法
  updateDbConfig(db: "core" | "refactored", field: "host" | "port" | "database" | "username" | "password", value: string) {
    (self.dbConnections[db].config as any)[field] = value;
  },
  
  // 更新数据库名称方法
  updateDbName(db: "core" | "refactored", name: string) {
    // 注意：这里只是更新显示名称，不改变实际连接配置
    // 在实际应用中，你可能需要更复杂的逻辑来处理名称和配置的关联
  },
  
  // 数据库卡片相关方法
  addDbCard(card: any) {
    self.dbCards.push(card);
  },
  
  removeDbCard(id: number) {
    const index = self.dbCards.findIndex(card => card.id === id);
    if (index !== -1) {
      self.dbCards.splice(index, 1);
    }
  },
  
  // 移除已连接的数据库卡片（从配置区域移除，但保留在已连接区域）
  removeConnectedDbCard(id: number) {
    const card = self.dbCards.find(card => card.id === id);
    if (card) {
      // 将已连接的卡片添加到已连接区域
      if (card.isConnected) {
        // 检查是否已存在于connectedDbCards中
        const exists = self.connectedDbCards.some(c => c.id === id);
        if (!exists) {
          self.connectedDbCards.push({
            id: card.id,
            name: card.name,
            config: { ...card.config },
            isConnected: card.isConnected
          });
        }
      }
      
      // 从配置区域移除卡片
      const index = self.dbCards.findIndex(card => card.id === id);
      if (index !== -1) {
        self.dbCards.splice(index, 1);
      }
      
      // 如果删除后没有数据库卡片了，则添加一个新的
      if (self.dbCards.length === 0) {
        const newCard = {
          id: Date.now(),
          name: '自定义数据库名称',
          config: {
            host: "",
            port: "",
            database: "",
            username: "",
            password: ""
          },
          isConnected: false
        };
        self.dbCards.push(newCard);
      }
      
      // 如果只剩一个卡片，也添加一个新的
      if (self.dbCards.length === 1) {
        const newCard = {
          id: Date.now() + 1, // 确保ID唯一
          name: '自定义数据库名称',
          config: {
            host: "",
            port: "",
            database: "",
            username: "",
            password: ""
          },
          isConnected: false
        };
        self.dbCards.push(newCard);
      }
    }
  },
  
  updateDbCardConfig(id: number, field: string, value: string) {
    const card = self.dbCards.find(card => card.id === id);
    if (card) {
      (card.config as any)[field] = value;
    }
    
    // 同时更新已连接区域的卡片配置
    const connectedCard = self.connectedDbCards.find(card => card.id === id);
    if (connectedCard) {
      (connectedCard.config as any)[field] = value;
    }
  },
  
  setDbCardConnected(id: number, connected: boolean) {
    const card = self.dbCards.find(card => card.id === id);
    if (card) {
      card.isConnected = connected;
      
      // 如果连接成功，同时添加到已连接数据库列表
      if (connected) {
        // 检查是否已存在于connectedDbCards中
        const exists = self.connectedDbCards.some(c => c.id === id);
        if (!exists) {
          self.connectedDbCards.push({
            id: card.id,
            name: card.name,
            config: { ...card.config },
            isConnected: card.isConnected
          });
        }
      }
    }
  },
  
  // 连接成功后移除卡片并在必要时添加新卡片
  setDbCardConnectedAndManageCards(id: number, connected: boolean) {
    const card = self.dbCards.find(card => card.id === id);
    if (card) {
      card.isConnected = connected;
      
      // 如果连接成功，同时添加到已连接数据库列表
      if (connected) {
        // 检查是否已存在于connectedDbCards中
        const exists = self.connectedDbCards.some(c => c.id === id);
        if (!exists) {
          self.connectedDbCards.push({
            id: card.id,
            name: card.name,
            config: { ...card.config },
            isConnected: card.isConnected
          });
        }
        
        // 检查是否只剩一个卡片
        if (self.dbCards.length === 1) {
          // 添加一个新的空卡片
          const newCard = {
            id: Date.now(),
            name: '自定义数据库名称',
            config: {
              host: "",
              port: "",
              database: "",
              username: "",
              password: ""
            },
            isConnected: false
          };
          self.dbCards.push(newCard);
        }
      }
    }
  },
  
  updateDbCardName(id: number, name: string) {
    const card = self.dbCards.find(card => card.id === id);
    if (card) {
      card.name = name;
    }
    
    // 同时更新已连接区域的卡片名称
    const connectedCard = self.connectedDbCards.find(card => card.id === id);
    if (connectedCard) {
      connectedCard.name = name;
    }
  },
  
  // 环境配置标签页切换方法
  setActiveEnvTab(tab: "db" | "var") {
    self.activeEnvTab = tab;
  },
  
  // 设置悬停的数据库ID
  setHoveredDbId(id: number | null) {
    self.hoveredDbId = id;
  },
  
  // 设置重构数据库连接状态
  setRefactoredDbConnected(connected: boolean) {
    self.dbConnections.refactored.isConnected = connected;
  },
  
  // 从已连接区域移除数据库卡片
  removeConnectedDbFromShow(id: number) {
    const index = self.connectedDbCards.findIndex(card => card.id === id);
    if (index !== -1) {
      self.connectedDbCards.splice(index, 1);
    }
    
    // 如果删除后没有数据库卡片了，则添加一个新的
    if (self.dbCards.length === 0) {
      const newCard = {
        id: Date.now(),
        name: '自定义数据库名称',
        config: {
          host: "",
          port: "",
          database: "",
          username: "",
          password: ""
        },
        isConnected: false
      };
      self.dbCards.push(newCard);
    }
  }
}));